package com.istock.union.controller.vue;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.istock.base.common.api.model.ApiBaseResponse;
import com.istock.base.common.api.model.RetStatusEnum;
import com.istock.base.spring.dynamicLoad.PropertyStaticLoader;
import com.istock.union.user.client.SSOClientUtils;
import com.istock.union.user.model.Constants;
import com.istock.union.user.model.SSOUser;
import com.istock.union.user.model.TenantInfo;
import com.istock.union.user.security.InnerTokenService;
import com.istock.union.user.service.AschTaskService;
import com.istock.union.user.service.TenantInfoService;
import com.istock.union.user.utils.WebCommonUtils;

@RequestMapping("pre/vue")
@Controller
public class TenantController {

	@Autowired
	private TenantInfoService tenantInfoService;
	
	@Autowired
	private InnerTokenService tokenService;

	@Autowired
	private AschTaskService asycRecord;
	
	@Value("${sso.login.verifyCount:3}")
	private Integer overVerifyCount;
	
	@Value("${sso.token.name:logintoken}")
	private String tokenName;

	@Value("${sso.token.storeType:cookie}")
	private String storeType;
	
	@RequestMapping("findTenantList")
	@ResponseBody
	public ApiBaseResponse<List<TenantInfo>> findTenantList(){
		List<TenantInfo> tenantList = tenantInfoService.findAllTenantList();
		return new ApiBaseResponse<>(RetStatusEnum.SUCCESS,Constants.API_RESPONSE_SUCCESS_CODE,Constants.API_RESPONSE_SUCCESS_MESSAGE , tenantList);
	}
	
	/**
	 * 配置信息
	 * @param request
	 * @return
	 */
	@RequestMapping("property")
	@ResponseBody
	public ApiBaseResponse<Map<String,Object>> property(HttpServletRequest request){
		Map<String,Object> result = new HashMap<String,Object>();

		// 是否需要租户选择下拉框
		result.put("multipleCorporate",Boolean.valueOf(PropertyStaticLoader.getInstance().findProperty("system.mutiable", "false")));

		// 是否需要校验码
		HttpSession session = request.getSession(true);
		Integer loginTime = NumberUtils.toInt(session.getAttribute("loginTime") + "", 0);
		Boolean needVerify =overVerifyCount >= 0 && loginTime >= overVerifyCount;
		result.put("needVerify",needVerify);


		return new ApiBaseResponse<>(RetStatusEnum.SUCCESS,Constants.API_RESPONSE_SUCCESS_CODE,Constants.API_RESPONSE_SUCCESS_MESSAGE , result);
	}
	
	/**
	 * sso的登出 所有的登出必须交给sso的登出 由sso负责调用外部的登出逻辑
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("vueLogout")
	@ResponseBody
	public ApiBaseResponse<String> logout(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
		String token = WebCommonUtils.findToken(request, tokenName);
		if (StringUtils.isNotBlank(token)) {
			SSOUser ssoUser = tokenService.verify(token);
			if (ssoUser != null) {
				SSOClientUtils.getInstance().setCurrent(token);
				// 清空服务器的token,以及所有的ticket
				tokenService.invalidToken(token);
				SSOClientUtils.getInstance().removeObject(token);
			}
		}

		// 将token从浏览器清除
		if (storeType.equalsIgnoreCase("cookie")) {
			if(request.getCookies() != null){
				for (Cookie cookie : request.getCookies()) {
					if ((tokenName.equalsIgnoreCase(cookie.getName()))) {
						WebCommonUtils.removeCookie(response, cookie.getName());
//						continue;
					}
				}
			}
		}

		// 用户下线
		asycRecord.userOnlineRemove(new String[] {token});//userOnlineRemove(token);
		//return toRedirect(model, WebCommonUtils.urlContact(request.getContextPath(), loginUrl));
		return new ApiBaseResponse<>(RetStatusEnum.SUCCESS,Constants.API_RESPONSE_SUCCESS_CODE, Constants.API_RESPONSE_SUCCESS_MESSAGE , "");
	}
}
